// 加速度传感器 X 轴，5秒512个数据（数据时间间隔：10ms）
define(function(require){
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");
	var echarts  = require("../lib/echarts/echarts-all-min");
	//var macarons = require('../lib/echarts/theme/macarons');
	var mqtt = require("../mqttclient/mqtt-baidu");
	require("../lib/moment.min");
	
	var comm = require('../lib/user/comm');
	
	
	var Model = function(){
		this.callParent();
		this.chart = null;
		this.chartData = [];
		this.chartDataTemp = [];
		this.chartDataMax = 100;		// 10ms 一个数据
		this.chartHeight = justep.Bind.observable('200px');  // 默认 chart 高度
		
		this.timerChartRender = null;
	};

    Model.prototype.test = function() {
    	alert('test ok');
    }
    
	Model.prototype.doConnect = function () {
    };

	Model.prototype.doMsgArrivedAccelX = function (message) {
		var rr = this.addDataBuff(message.payloadBytes);
		var lengh = message.payloadBytes.byteLength;
		var timestr = moment(rr.time).format(comm.gParams.timeFormat.std);
		var timestrB = moment(rr.timeB).format(comm.gParams.timeFormat.std);
    };

    Model.prototype.addDataBuff = function(buff) {
		var vb = new Uint8Array(buff);
		var year = vb[0] + vb[1]*256;
		var time = moment([year, vb[2]-1, vb[3], vb[4], vb[5], vb[6], 0]); // 初始化是月从0开始；0=1月
		var timeB = moment(time).subtract(5, 'seconds');
		for (var i = 0; i < 500; i++) {
			var val = vb[i*2+7] + vb[i*2+8]*256;
			var tt = moment(timeB).add(10*i, 'ms').format(comm.gParams.timeFormat.std2ms);
		    this.dataAppend(tt, val);
		}
		return {time: time, timeB: timeB};
    }

	// 将数据保存到 this.chartData 中；timestr=x轴; val=y轴
    Model.prototype.dataAppend = function(timestr, val) {
    	var data = {
    		name: timestr,
    		value: [ timestr, val ]
    	};

        this.chartDataTemp.push(data);

    	return data;
    }
    
	// 在 chart 上绘制 this.chartData 数据；20ms执行一次，每次2个数据
    Model.prototype.dataRender = function() {
    	// 1. 将 this.chartDataTemp 的数据挪到 this.charData 中
    	for(var i=0; i<this.chartDataTemp.length && i <2; i++ ){
	    	while(this.chartData.length >= this.chartDataMax) {
	    		this.chartData.shift();
	    	}
	    	this.chartData.push(this.chartDataTemp[0]);
	    	this.chartDataTemp.shift();
    	}

	    this.chart.setOption({
	        series: [{
	            data: this.chartData
	        }]
	    });
    };
    
    Model.prototype.chartInit = function(chartHeight) {
        var option = {
        	title: {
        		text: '振动检测',
        		left: '36px',
        		textStyle: {
        			fontSize: '14',
        		}
        	},
		    grid: {
		        left: '36px',
		        right: '20px',
		        top: '10px',
		        bottom: '20px',
		        containLabel: false,
		        show: false,
		    },
            toolbox: {
                show : true,
                feature : {
                    mark : {show: true},
                    dataView : {show: false, readOnly: false},		   // 数据弹窗
                    magicType : {show: false, type: ['line', 'bar']},  // 图表显示类型切换 
                    restore : {show: true},							   // 刷新
                    saveAsImage : {show: true}
                }
            },

            tooltip : {
                trigger: 'axis'
            },
            
		    xAxis: [{
		        type: 'time',
		        interval: 500,
		        splitLine: {
		            show: false,
		        }
		    }],
		    yAxis: {
		        type: 'value',
		        scale: false,
		        min: 950,       // 900,
		        max: 1050,		// 1100,
		        interval: 25,
		        //splitNumber: 3,
		        boundaryGap: [0, '100%'],
		        splitLine: {
		            show: false,
		        },
		        splitArea: {
		        	show: true,
		        	areaStyle: {
		        		color: ['rgba(250,250,250,0.5)','rgba(200,200,200,0.5)'],
		        	},
		        },
		    },
		    
		    series: [{
		        name: '实时数据',
		        type: 'line',
		        showSymbol: false,
		        hoverAnimation: false,
		        data: this.chartData
		    }],
            
            legend: {
                data:['实时数据','降水量']
            },

            calculable : true,

        };
        
		//var theme = new Theme();
		//echarts.registerTheme("macarons", theme.getTheme("macarons"));        
		this.chartHeight.set(chartHeight);
		this.chart = echarts.init(this.getElementByXid('pnlChart'));
        var myChart = this.chart;
        myChart.setOption(option);
    };
    
    Model.prototype.modelLoad = function(event) {
    	var ch;
    	if(this.params.chartHeight)
    	{
    		ch = this.params.chartHeight;
    	}
    	else
    	{
        	ch = (window.innerHeight * 0.28).toFixed() + 'px';
    	}
    	this.chartInit(ch);

        var self = this;
		this.timerChartRender = setInterval(function () {
		    self.dataRender()
		}, 20);
        
		mqtt.onMsgArrivedAccelX = function(message) { self.doMsgArrivedAccelX(message);};    
    };
    
	Model.prototype.modelUnLoad = function(event){
		clearInterval(this.timerChartRender);
		mqtt.unsubscribe(comm.gParams.baiduTopics.accelX + '/#')
	};
    
    
	return Model;
});